package com.ideaaedi.zoo.diy.feature.i18n.impl.spring.core;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.i18n.AbstractLocaleResolver;

import javax.annotation.Nonnull;
import java.util.Arrays;
import java.util.Locale;

/**
 * {@link Locale}解析器
 *
 * @author <font size = "20" color = "#3CAA3C"><a href="https://gitee.com/JustryDeng">JustryDeng</a></font> <img
 * src="https://gitee.com/JustryDeng/shared-files/raw/master/JustryDeng/avatar.jpg" />
 * @since 1.0.0
 */
@Slf4j
public class ZooI18nSpringLocaleResolver extends AbstractLocaleResolver {
    
    /**
     * 符合国际标准(IETF RFC 5646)的语言标签
     * <pre>
     * 注：语言标签可通过{@link Locale#toLanguageTag()}获取.
     *      中国内陆：  Locale.CHINA.toLanguageTag()   结果为  zh-CN
     *      中国台湾省：Locale.TAIWAN.toLanguageTag()  结果为  zh-TW
     *      美国：      Locale.US.toLanguageTag()     结果为  en-US
     * </pre>
     */
    private static final String[] LOCAL_KEY = {"language", "lang"};
    
    public ZooI18nSpringLocaleResolver() {
    }
    
    @Nonnull
    @Override
    public Locale resolveLocale(@Nonnull HttpServletRequest request) {
        // 从请求头中拿前端传的local信息
        String languageTag = Arrays.stream(LOCAL_KEY)
                .map(request::getHeader)
                .filter(StringUtils::isNotBlank)
                .findFirst()
                .orElse(null);
        Locale locale;
        if (StringUtils.isNotBlank(languageTag)) {
            try {
                locale = Locale.forLanguageTag(languageTag);
                return locale;
            } catch (Exception e) {
                log.warn("parse Local instance occur error. e.getMessage() -> {}", e.getMessage());
            }
        }
        Locale defaultLocale = getDefaultLocale();
        locale = defaultLocale != null ? defaultLocale : request.getLocale();
        if (locale == null) {
            locale = Locale.SIMPLIFIED_CHINESE;
        }
        return locale;
    }
    
    @Override
    public void setLocale(@Nonnull HttpServletRequest request, HttpServletResponse response, Locale locale) {
        throw new UnsupportedOperationException("Cannot change HTTP lang header - use a different locale resolution strategy");
    }
    
}